package com.hzh.scala

import java.io.{BufferedReader, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo3IO {
  def main(args: Array[String]): Unit = {
    /**
     * 读取文件
     * 1、可以使用java中的方法
     * 2、在 scala中有source
     *
     */
    //使用java中的io流
    val br = new BufferedReader(new FileReader("data/words.txt"))
    //读取第一行
    var line: String = br.readLine()
    //判断下一行是否为空
    while (line!=null){
      println(line)
      //每次循环读取下一行
      line = br.readLine()
    }
    br.close()

      //scala中的方式
    val bufferedSource: BufferedSource = Source.fromFile("data/words.txt")
    //读取所有行，得到一个迭代器
    val iterator: Iterator[String] = bufferedSource.getLines()
    for (elem:String <- iterator) {
      print(elem)
    }
    bufferedSource.close()

    /**
     * 写文件
     *
     */
    val fileWriter = new FileWriter("data/out1.txt")
    fileWriter.write("java")
    fileWriter.write("\n")
    fileWriter.write("java1")
    fileWriter.write("\n")
    fileWriter.write("java2")
    fileWriter.close()







  }
}
